package com.cgx.websocket;

import com.cgx.websocket.handler.WebSocketEventHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenguanxin
 * @date 2021-05-13 20:55
 */
@Component
public class MyWebSocketHandler implements WebSocketHandler {

    public static final ConcurrentHashMap<String, WebSocketSession> SESSION_MAP = new ConcurrentHashMap<>();

    @Autowired
    WebSocketEventHandler webSocketEventHandler;

    //连接关闭后
    @Override
    public void afterConnectionClosed(WebSocketSession arg0, CloseStatus arg1) throws Exception {
        // TODO Auto-generated method stub
        try {
            webSocketEventHandler.afterConnectionClosed(arg0, arg1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //连接建立后
    @Override
    public void afterConnectionEstablished(WebSocketSession arg0) throws Exception {
        // TODO Auto-generated method stub
        try {
            webSocketEventHandler.afterConnectionEstablished(arg0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //收到消息后
    @Override
    public void handleMessage(WebSocketSession arg0, WebSocketMessage<?> arg1) throws Exception {
        // TODO Auto-generated method stub
        try {
            webSocketEventHandler.handleMessage(arg0, arg1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //错误后(客户端强制断开)
    @Override
    public void handleTransportError(WebSocketSession arg0, Throwable arg1) throws Exception {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean supportsPartialMessages() {
        // TODO Auto-generated method stub
        return false;
    }
}
